import 'package:get/get.dart';
import 'package:raze/lore/glyph/circle_essence.dart';
import 'package:raze/lore/glyph/circle_membership.dart';
import 'package:raze/lore/glyph/circle_message_essence.dart';

/// 圈子状态管理
/// 全局圈子状态，提供圈子查询、加入、退出、消息发送等功能
class CircleChronicle extends GetxController {
  // 所有圈子列表
  final _circleList = <CircleEssence>[].obs;

  // 所有成员关系列表
  final _membershipList = <CircleMembership>[].obs;

  // 所有圈子消息列表
  final _messageList = <CircleMessageEssence>[].obs;

  /// 获取所有圈子列表
  List<CircleEssence> get circleList => _circleList;

  /// 获取所有成员关系列表
  List<CircleMembership> get membershipList => _membershipList;

  /// 获取所有消息列表
  List<CircleMessageEssence> get messageList => _messageList;

  @override
  void onInit() {
    super.onInit();
    _initializeDefaultCircles();
  }

  /// 初始化默认圈子数据
  void _initializeDefaultCircles() {
    final now = DateTime.now();

    // 初始化圈子
    _circleList.value = [
      CircleEssence(
        id: '1',
        image: 'assets/images/circle1.png',
        title: 'AfterRain Club',
      ),
      CircleEssence(
        id: '2',
        image: 'assets/images/circle2.png',
        title: 'Leaf Whisperers',
      ),
      CircleEssence(
        id: '3',
        image: 'assets/images/circle3.png',
        title: 'Rainlight Observers',
      ),
      CircleEssence(
        id: '4',
        image: 'assets/images/circle4.png',
        title: 'Drops & Roots',
      ),
    ];

    // 初始化成员关系
    // 用户2加入圈子1和2
    // 用户3加入圈子1、2、3
    // 用户4加入圈子2和4
    // 用户5加入圈子1
    _membershipList.value = [
      // 圈子1的成员
      CircleMembership(circleId: '1', userId: '2'),
      CircleMembership(circleId: '1', userId: '3'),
      CircleMembership(circleId: '1', userId: '5'),
      // 圈子2的成员
      CircleMembership(circleId: '2', userId: '2'),
      CircleMembership(circleId: '2', userId: '3'),
      CircleMembership(circleId: '2', userId: '4'),
      // 圈子3的成员
      CircleMembership(circleId: '3', userId: '3'),
      CircleMembership(circleId: '3', userId: '6'),
      // 圈子4的成员
      CircleMembership(circleId: '4', userId: '4'),
      CircleMembership(circleId: '4', userId: '7'),
    ];

    // 初始化圈子消息
    _messageList.value = [
      // 圈子1 (AfterRain Club) 的消息
      CircleMessageEssence(
        id: '2',
        circleId: '1',
        userId: '2',
        content:
            'The leaves on my plants look so fresh after yesterday\'s rain!',
        createTime: now.subtract(const Duration(days: 4, hours: 10)),
      ),
      CircleMessageEssence(
        id: '3',
        circleId: '1',
        userId: '3',
        content:
            'I noticed tiny water droplets forming perfect beads on the leaf surfaces.',
        createTime: now.subtract(const Duration(days: 4, hours: 8)),
      ),
      CircleMessageEssence(
        id: '5',
        circleId: '1',
        userId: '5',
        content:
            'My garden is blooming like never before! The rain really helped.',
        createTime: now.subtract(const Duration(days: 3)),
      ),

      // 圈子2 (Leaf Whisperers) 的消息
      CircleMessageEssence(
        id: '7',
        circleId: '2',
        userId: '2',
        content:
            'I love observing how leaves change color after absorbing rainwater.',
        createTime: now.subtract(const Duration(days: 5, hours: 12)),
      ),
      CircleMessageEssence(
        id: '8',
        circleId: '2',
        userId: '3',
        content:
            'The green color becomes so much more vibrant! It\'s fascinating.',
        createTime: now.subtract(const Duration(days: 5, hours: 10)),
      ),
      CircleMessageEssence(
        id: '9',
        circleId: '2',
        userId: '4',
        content:
            'Has anyone noticed how some leaves have a waxy surface that repels water?',
        createTime: now.subtract(const Duration(days: 4, hours: 18)),
      ),

      // 圈子3 (Rainlight Observers) 的消息
      CircleMessageEssence(
        id: '12',
        circleId: '3',
        userId: '3',
        content:
            'The way sunlight reflects off raindrops on leaves creates such beautiful patterns!',
        createTime: now.subtract(const Duration(days: 6, hours: 14)),
      ),
      CircleMessageEssence(
        id: '13',
        circleId: '3',
        userId: '6',
        content:
            'I captured some amazing photos during the golden hour after rain.',
        createTime: now.subtract(const Duration(days: 6, hours: 12)),
      ),

      // 圈子4 (Drops & Roots) 的消息
      CircleMessageEssence(
        id: '16',
        circleId: '4',
        userId: '4',
        content:
            'After heavy rain, I noticed the soil becomes much easier to work with.',
        createTime: now.subtract(const Duration(days: 7, hours: 16)),
      ),
      CircleMessageEssence(
        id: '17',
        circleId: '4',
        userId: '7',
        content: 'Rainwater helps nutrients reach the roots more effectively.',
        createTime: now.subtract(const Duration(days: 7, hours: 14)),
      ),
      CircleMessageEssence(
        id: '19',
        circleId: '4',
        userId: '4',
        content:
            'I\'ve been tracking my plants\' growth after each rainfall - the difference is remarkable!',
        createTime: now.subtract(const Duration(days: 5, hours: 6)),
      ),
    ];
  }

  /// 根据ID查询圈子
  /// [circleId] 圈子ID
  /// 返回圈子，不存在返回null
  CircleEssence? queryCircleById(String circleId) {
    return _circleList.firstWhereOrNull((circle) => circle.id == circleId);
  }

  /// 加入圈子
  /// [circleId] 圈子ID
  /// [userId] 用户ID
  /// 返回操作结果，成功返回true，失败返回false（已加入或圈子不存在）
  bool joinCircle(String circleId, String userId) {
    // 检查圈子是否存在
    final circleExists = _circleList.any((circle) => circle.id == circleId);
    if (!circleExists) {
      return false; // 圈子不存在
    }

    // 检查是否已加入
    final alreadyJoined = _membershipList.any(
      (membership) =>
          membership.circleId == circleId && membership.userId == userId,
    );

    if (alreadyJoined) {
      return false; // 已加入
    }

    // 创建成员关系
    final newMembership = CircleMembership(circleId: circleId, userId: userId);

    _membershipList.add(newMembership);
    return true;
  }

  /// 退出圈子
  /// [circleId] 圈子ID
  /// [userId] 用户ID
  /// 返回操作结果，成功返回true，失败返回false（未加入）
  bool leaveCircle(String circleId, String userId) {
    final index = _membershipList.indexWhere(
      (membership) =>
          membership.circleId == circleId && membership.userId == userId,
    );

    if (index == -1) {
      return false; // 未加入
    }

    _membershipList.removeAt(index);
    return true;
  }

  /// 检查用户是否已加入圈子
  /// [circleId] 圈子ID
  /// [userId] 用户ID
  /// 返回是否已加入
  bool checkIsMember(String circleId, String userId) {
    return _membershipList.any(
      (membership) =>
          membership.circleId == circleId && membership.userId == userId,
    );
  }

  /// 获取圈子的所有成员ID列表
  /// [circleId] 圈子ID
  /// 返回该圈子的所有成员ID列表
  List<String> fetchCircleMembers(String circleId) {
    return _membershipList
        .where((membership) => membership.circleId == circleId)
        .map((membership) => membership.userId)
        .toList();
  }

  /// 获取用户加入的所有圈子ID列表
  /// [userId] 用户ID
  /// 返回该用户加入的所有圈子ID列表
  List<String> fetchUserCircles(String userId) {
    return _membershipList
        .where((membership) => membership.userId == userId)
        .map((membership) => membership.circleId)
        .toList();
  }

  /// 获取圈子的成员数量
  /// [circleId] 圈子ID
  /// 返回成员数量
  int countCircleMembers(String circleId) {
    return _membershipList
        .where((membership) => membership.circleId == circleId)
        .length;
  }

  /// 发送圈子消息
  /// [circleId] 圈子ID
  /// [userId] 发送者用户ID
  /// [content] 消息内容
  /// 返回创建的消息ID
  String postCircleMessage(String circleId, String userId, String content) {
    // 检查用户是否是圈子成员
    final isMember = checkIsMember(circleId, userId);
    if (!isMember) {
      throw Exception('User is not a member of this circle');
    }

    final newId = (_messageList.length + 1).toString();
    final newMessage = CircleMessageEssence(
      id: newId,
      circleId: circleId,
      userId: userId,
      content: content,
      createTime: DateTime.now(),
    );
    _messageList.add(newMessage);
    return newId;
  }

  /// 获取圈子的所有消息列表
  /// [circleId] 圈子ID
  /// 返回按时间排序的该圈子的所有消息列表
  List<CircleMessageEssence> fetchCircleMessages(String circleId) {
    return _messageList.where((msg) => msg.circleId == circleId).toList()
      ..sort((a, b) => a.createTime.compareTo(b.createTime));
  }

  /// 删除圈子的所有消息
  /// [circleId] 圈子ID
  /// 返回操作结果，成功返回true，失败返回false（圈子不存在或没有消息）
  bool purgeCircleMessages(String circleId) {
    final initialCount = _messageList.length;
    _messageList.removeWhere((msg) => msg.circleId == circleId);
    return _messageList.length < initialCount;
  }
}
